package com.lt.utils.SocketUtils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class Upload implements Runnable {
    private final ArrayList<String> jsonLists;
    private final Context context;

    private DataOutputStream dos = null;
    private Boolean fS = true;
    private String string;
    private final Handler handler;

    public Upload(Context context, ArrayList<String> jsonLists, Socket client, Handler handler) {
        this.jsonLists = jsonLists;
        this.context = context;
        this.handler = handler;
        OutputStream ops;
        try {
            ops = client.getOutputStream();
            dos = new DataOutputStream(ops);
        } catch (IOException e) {
            e.printStackTrace();
            fS = false;
            CloseUtil.CloseAll(client, dos);
        }
    }

    public void Send() {
        handler.sendEmptyMessage(0x30);
        int counts = jsonLists.size();
        Message message = new Message();
        message.what = 0x33;
        message.obj = counts;
        handler.sendMessage(message);
        if (counts < 1) {
            handler.sendEmptyMessage(0x10);
        } else {
            for (int i = 0; i < counts; i++) {
                try {
                    dos.writeUTF(jsonLists.get(i));
                    if (i == counts / 2) {
                        handler.sendEmptyMessage(0x31);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    fS = false;
                    handler.sendEmptyMessage(0x22);
                    CloseUtil.CloseAll(dos);
                }
                int j = counts - 1;
                if (i == j) {
                    handler.sendEmptyMessage(0x32);
                }
            }
        }

    }

    @Override
    public void run() {
        if (fS) {
            Send();
        } else {
            handler.sendEmptyMessage(0x22);
        }

    }
}
